<?
require_once ("library/Settings.php");

function GetFileDataByCategory($category)
{
	return GetFileDataByCategoryNum($category, 0);
}

function GetFileDataByCategoryNum($category,$num)
{
	$extra = '';
	if ($num > 0) $extra = ' LIMIT 0,'.$num;
	switch ($category)
	{
		case -1: //All Notes
			return  noter_querty('files', $extra);
			break;
		case -2: //Recent Notes
			$s = 86400; //seconds in a day
			$time = time() - ($s * 7); //unix time for 1 week ago.
			return noter_querty('files', 'WHERE time > '.$time.' ORDER BY time DESC'.$extra);
			break;
		case -3: //Top Downloads
			return noter_querty('files', 'ORDER BY downloads DESC'.$extra);
			break;
		default:
			return  noter_querty('files', "WHERE category=$category".$extra);	
			break;
	}

}

function GetFileDataById($id)
{
	switch ($id)
	{
		default:
			return  noter_querty('files', "WHERE id=$id");
			break;
		break;	
	}
}

function CheckLogin($u, $p)
{
	$p = md5($p);
	$users =  noter_querty('users', "WHERE email=\"$u\" AND password=\"$p\"");

	if (count($users) > 0)
	{
		return $users[0];
	}
	return -1;
}

function GetUserDataById($uid)
{
	switch ($uid)
	{
		default:
			$users =  noter_querty('users', "WHERE id=$uid");
			$user = $users[0];
			$db = ConnectToDB();
			$query = "SELECT count(id) from files WHERE uploader=$uid";
			$result = mysql_query($query);
	
			$array  = array();
			while ($row = mysql_fetch_assoc($result))
			{
				$array[] = $row;
			}	

			$users[0]['uploads'] = $array[0]['count(id)'];
			return $users;

		break;
		
	}
}

function GetCategoryName($cid)
{
	$a = noter_querty('subjects', "WHERE id=$cid");
	$b = $a[0]['name'];
	return  ucfirst($b);
}
function GetCategoryNames()
{
	$a = noter_querty('subjects', 'ORDER BY name');
	$array = array();
	foreach ($a as $row)
	{
		$array[] = array('id'=>$row['id'], 'name'=>ucfirst($row['name']));
	}	

	return  $array;
}
function GetTopSharers($num)
{	
	$extra = '';
	if ($num > 0) $extra = ' LIMIT 0,'.$num;
	$query = 'SELECT uploader, count(id) FROM files GROUP BY uploader'.$extra;
	$db = ConnectToDB();
	$result = mysql_query($query);
	$array  = array();
	while ($row = mysql_fetch_assoc($result))
	{
		$array[] = $row;
	}	
	$out = array();
	
	foreach($array as $a)
	{
		$out[] = array('name' => GetUserDataById($a['uploader']), 'count'=>$a['count(id)']);
	}
	return $out;
}
function noter_querty($table, $param)
{
	$whereClause = '';
	if (strlen($param) > 0)
		$whereClause = "$param";
	$db = ConnectToDB();
	$query = "SELECT * from $table $whereClause";
	
	$result = mysql_query($query);
	
	$array  = array();
	while ($row = mysql_fetch_assoc($result))
	{
		$array[] = $row;
	}	
	return $array;
}

?>
